<script setup lang="ts">
import type { InventoryDetail, InventoryTransaction } from '../types';

import { nextTick, ref } from 'vue';

import { BasicModal, BasicTable, useVbenModal } from '@vben/uikit';

import { $t } from '#/locales';
import { formatCurrency, formatTime } from '#/utils/format';

import { useMovementColumns } from '../data';
import { getInventoryTransactions } from '../services';

const modalId = 'inventory-detail-modal';
const [Modal, modalApi] = useVbenModal({
  title: $t('inventory.detailModal.title'),
  fullscreenButton: false,
  showOkButton: false,
  showCancelButton: true,
  width: 800,
});



const inventoryData = ref<InventoryDetail | null>(null);
const movementTableData = ref<InventoryTransaction[]>([]);
const loading = ref(false);
const movementLoading = ref(false);

// 移动历史表格列配置
const movementColumns = useMovementColumns();

// 获取物料类型标签
const getMaterialTypeLabel = (type: string): string => {
  const typeMap: Record<string, string> = {
    raw_material: $t('inventory.materialType.rawMaterial'),
    semi_finished: $t('inventory.materialType.semiFinished'),
    finished_goods: $t('inventory.materialType.finishedGoods'),
    packaging_material: $t('inventory.materialType.packagingMaterial'),
  };
  return typeMap[type] || '-';
};

// 获取状态标签
const getStatusLabel = (status: string): string => {
  const statusMap: Record<string, string> = {
    normal: $t('inventory.status.normal'),
    warning: $t('inventory.status.warning'),
    shortage: $t('inventory.status.shortage'),
    excess: $t('inventory.status.excess'),
  };
  return statusMap[status] || '-';
};

// 获取状态颜色
const getStatusColor = (status: string): string => {
  const colorMap: Record<string, string> = {
    normal: '#52c41a',
    warning: '#faad14',
    shortage: '#ff4d4f',
    excess: '#1890ff',
  };
  return colorMap[status] || '#d9d9d9';
};

// 获取交易记录数据
const getTransactionHistory = async (inventoryId: string): Promise<void> => {
  try {
    movementLoading.value = true;
    const res = await getInventoryTransactions({ inventory_id: inventoryId });
    // 格式化仓库和库位名称，确保即使为undefined也能正常显示
    movementTableData.value = res.data.map((item: InventoryTransaction) => ({
      ...item,
      from_warehouse_name: item.from_warehouse_name || '-',
      to_warehouse_name: item.to_warehouse_name || '-',
      from_location_name: item.from_location_name || '-',
      to_location_name: item.to_location_name || '-',
    }));
  } catch (error) {
    console.error('Failed to get inventory transactions:', error);
  } finally {
    movementLoading.value = false;
  }
};

// 打开模态框
function handleOpenModal(row: InventoryDetail): void {
  inventoryData.value = row;
  modalApi.setData(row);
  modalApi.open();
  nextTick(() => {
    if (row.inventory_id) {
      getTransactionHistory(row.inventory_id.toString());
    }
  });
}

// 导出方法供父组件使用
defineExpose({
  openModal: handleOpenModal,
  modalApi,
});
</script>
<template>
  <Modal>
    <div v-if="inventoryData" class="inventory-detail-content">
      <div class="detail-section">
        <h3 class="section-title">
          {{ $t('inventory.detailModal.basicInfo') }}
        </h3>
        <div class="detail-grid">
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.productCode') }}：</span
            >
            <span class="detail-value">{{
              formData?.product_code || '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.productName') }}：</span
            >
            <span class="detail-value">{{
              formData?.product_name || '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.specification') }}：</span
            >
            <span class="detail-value">{{
              formData?.specification || '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.unit') }}：</span
            >
            <span class="detail-value">{{ formData?.unit || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.materialType') }}：</span
            >
            <span class="detail-value">{{
              getMaterialTypeLabel(formData?.material_type)
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.batchNumber') }}：</span
            >
            <span class="detail-value">{{
              formData?.batch_number || '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.expiryDate') }}：</span
            >
            <span class="detail-value">{{
              formData?.expiry_date ? formatTime(formData.expiry_date) : '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.supplier') }}：</span
            >
            <span class="detail-value">{{
              formData?.supplier_name || '-'
            }}</span>
          </div>
        </div>
      </div>

      <div class="detail-section">
        <h3 class="section-title">
          {{ $t('inventory.detailModal.inventoryInfo') }}
        </h3>
        <div class="detail-grid">
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.warehouse') }}：</span
            >
            <span class="detail-value">{{
              formData?.warehouse?.warehouse_name || '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.location') }}：</span
            >
            <span class="detail-value">{{
              formData?.location?.location_name || '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.currentQuantity') }}：</span
            >
            <span class="detail-value">{{
              formData?.current_quantity || 0
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.safetyStock') }}：</span
            >
            <span class="detail-value">{{ formData?.safety_stock || 0 }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.minStock') }}：</span
            >
            <span class="detail-value">{{ formData?.min_stock || 0 }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.maxStock') }}：</span
            >
            <span class="detail-value">{{ formData?.max_stock || 0 }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.status') }}：</span
            >
            <span
              class="detail-value"
              :style="{ color: getStatusColor(formData?.status) }"
              >{{ getStatusLabel(formData?.status) }}</span
            >
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.lastCheck') }}：</span
            >
            <span class="detail-value">{{
              formData?.last_check_date
                ? formatTime(formData.last_check_date)
                : '-'
            }}</span>
          </div>
        </div>
      </div>

      <div class="detail-section">
        <h3 class="section-title">
          {{ $t('inventory.detailModal.valueInfo') }}
        </h3>
        <div class="detail-grid">
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.costPrice') }}：</span
            >
            <span class="detail-value"
              >¥{{ formatCurrency(formData?.unit_cost || 0) }}</span
            >
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.salePrice') }}：</span
            >
            <span class="detail-value"
              >¥{{ formatCurrency(formData?.sale_price || 0) }}</span
            >
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.inventoryCost') }}：</span
            >
            <span class="detail-value"
              >¥{{
                formatCurrency(
                  (formData?.current_quantity || 0) *
                    (formData?.unit_cost || 0),
                )
              }}</span
            >
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('inventory.detailModal.inventoryValue') }}：</span
            >
            <span class="detail-value"
              >¥{{
                formatCurrency(
                  (formData?.current_quantity || 0) *
                    (formData?.sale_price || 0),
                )
              }}</span
            >
          </div>
        </div>
      </div>

      <div class="detail-section">
        <h3 class="section-title">{{ $t('common.db_field.create_time') }}</h3>
        <div class="detail-grid">
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('common.db_field.creator') }}：</span
            >
            <span class="detail-value">{{ formData?.creator || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('common.db_field.create_time') }}：</span
            >
            <span class="detail-value">{{
              formData?.create_time ? formatTime(formData.create_time) : '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('common.db_field.modifier') }}：</span
            >
            <span class="detail-value">{{ formData?.modifier || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('common.db_field.update_time') }}：</span
            >
            <span class="detail-value">{{
              formData?.update_time ? formatTime(formData.update_time) : '-'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label"
              >{{ $t('common.db_field.is_deleted') }}：</span
            >
            <span class="detail-value">{{
              formData?.is_deleted ? '是' : '否'
            }}</span>
          </div>
        </div>
      </div>

      <div class="detail-section">
        <h3 class="section-title">
          {{ $t('inventory.detailModal.movementHistory') }}
        </h3>
        <div class="movement-history">
          <BasicTable
            :columns="movementColumns"
            :data-source="movementTableData"
            :pagination="false"
            :loading="movementLoading"
            size="small"
          />
        </div>
      </div>
    </div>
  </Modal>
</template>
<style lang="less" scoped>
.inventory-detail-content {
  padding: 20px 0;
}

.detail-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: rgba(0, 0, 0, 0.85);
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-label {
  flex: 0 0 100px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.65);
}

.detail-value {
  flex: 1;
  color: rgba(0, 0, 0, 0.85);
}

.movement-history {
  margin-top: 16px;
}
</style>
